<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理</title>
    <link rel="stylesheet" href="/static/usermanage.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>

<body>
<div class="loading-overlay" id="loading">
    <div class="spinner"></div>
</div>

<div class="container">
    <div class="header">
        <h1><i class="fas fa-users-cog"></i> 普通用户管理</h1>
        <div class="search-box">
            <input type="text" id="searchInput" placeholder="输入关键词进行搜索...">
        </div>
    </div>

    <table id="userTable">
        <thead>
        <tr>
            <th data-sort="uid">UID <i class="fas fa-sort"></i></th>
            <th data-sort="username">用户名 <i class="fas fa-sort"></i></th>
            <th data-sort="phonenumber">手机号 <i class="fas fa-sort"></i></th>
            <th data-sort="sex">性别 <i class="fas fa-sort"></i></th>
            <th data-sort="email">邮箱 <i class="fas fa-sort"></i></th>
            <th data-sort="create_at">注册时间 <i class="fas fa-sort"></i></th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody></tbody>
    </table>
</div>

<div class="toast" id="toast">请求失败，请检查网络连接</div>

<script>
    // 配置参数
    const config = {
        debounceTime: 300,
        sortIcons: {
            asc: 'fa-sort-up',
            desc: 'fa-sort-down'
        }
    };

    // 状态管理
    let currentData = [];
    let sortState = { column: 'uid', order: 'asc' };

    // 初始化
    $(document).ready(function () {
        setupEventListeners();
        loadUsers();
    });

    // 事件监听
    function setupEventListeners() {
        // 实时搜索
        $('#searchInput').on('input', debounce(handleSearch, config.debounceTime));

        // 表格排序
        $('#userTable th[data-sort]').on('click', function () {
            const column = $(this).data('sort');
            sortState.order = (sortState.column === column && sortState.order === 'asc') ? 'desc' : 'asc';
            sortState.column = column;
            updateSortUI();
            sortAndDisplayData();
        });

        // 为删除和修改按钮绑定事件（使用事件委托）
        $('#userTable tbody').on('click', '.delete-btn', handleDeleteUser);
        $('#userTable tbody').on('click', '.edit-btn', handleEditUser);
    }

    // 数据加载
    async function loadUsers(keyword) {
        showLoading(true);
        try {
            const url = keyword ? `/user/searchkw?kw=${encodeURIComponent(keyword)}` : '/user';
            const response = await fetch(url);
            if (!response.ok) throw new Error('请求失败');

            const data = await response.json();
            if (data.code === 0) {
                currentData = data.data;
                sortAndDisplayData();
            } else {
                showToast(data.msg || '获取数据失败');
            }
        } catch (error) {
            showToast(error.message);
            console.error('Error:', error);
        } finally {
            showLoading(false);
        }
    }

    // 数据显示
    function sortAndDisplayData() {
        const sortedData = [...currentData].sort((a, b) => {
            const valA = String(a[sortState.column] || '');
            const valB = String(b[sortState.column] || '');
            return sortState.order === 'asc'
                ? valA.localeCompare(valB)
                : valB.localeCompare(valA);
        });

        $('#userTable tbody').html(sortedData.map(user => `
                <tr>
                    <td data-label="UID">${user.uid}</td>
                    <td data-label="用户名">${user.username}</td>
                    <td data-label="手机号">${formatPhone(user.phonenumber)}</td>
                    <td data-label="性别">
                        <span class="badge ${user.sex.toLowerCase()}">${user.sex}</span>
                    </td>
                    <td data-label="邮箱"><a href="mailto:${user.email}">${user.email}</a></td>
                    <td data-label="注册时间">${formatDate(user.create_at)}</td>
                    <td>
                        <button class="edit-btn" data-uid="${user.uid}">修改</button>
                        <button class="delete-btn" data-uid="${user.uid}">删除</button>
                    </td>
                </tr>
            `).join(''));
    }

    // 删除用户
    async function handleDeleteUser() {
        const uid = $(this).data('uid');
        if (confirm('确定要删除该用户吗？')) {
            try {
                const response = await fetch(`/user/${uid}`, {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                const data = await response.json();
                if (data.code === 0) {
                    showToast('删除成功');
                    loadUsers();
                } else {
                    showToast(data.msg || '删除失败');
                }
            } catch (error) {
                showToast(error.message);
                console.error('Error:', error);
            }
        }
    }

    // 修改用户
    async function handleEditUser() {
        const uid = $(this).data('uid');
        console.log(uid)
        const user = currentData.find(u => u.uid === uid);
        const { value: formValues } = await Swal.fire({
            title: '修改用户信息',
            html: `
                    <input id="swal-username" class="swal2-input" placeholder="用户名" value="${user.username}">
                    <input id="swal-phonenumber" class="swal2-input" placeholder="手机号" value="${user.phonenumber}">
                    <select id="swal-sex" class="swal2-input">
                        <option value="男" ${user.sex === '男' ? 'selected' : ''}>男</option>
                        <option value="女" ${user.sex === '女' ? 'selected' : ''}>女</option>
                        <option value="隐藏" ${user.sex === '隐藏' ? 'selected' : ''}>隐藏</option>
                    </select>
                    <input id="swal-email" class="swal2-input" placeholder="邮箱" value="${user.email}">
                `,
            focusConfirm: false,
            preConfirm: () => {
                return {
                    username: document.getElementById('swal-username').value,
                    phonenumber: document.getElementById('swal-phonenumber').value,
                    sex: document.getElementById('swal-sex').value,
                    email: document.getElementById('swal-email').value
                };
            }
        });

        if (formValues) {
            try {
                const response = await fetch(`/user/${uid}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        username: formValues.username,
                        phonenumber: formValues.phonenumber,
                        sex: formValues.sex,
                        email: formValues.email
                    })
                });
                const data = await response.json();
                if (data.code === 0) {
                    showToast('修改成功');
                    loadUsers();
                } else {
                    showToast(data.msg || '修改失败');
                }
            } catch (error) {
                showToast(error.message);
                console.error('Error:', error);
            }
        }
    }

    // 工具函数
    function debounce(fn, delay) {
        let timeout;
        return (...args) => {
            clearTimeout(timeout);
            timeout = setTimeout(() => fn.apply(this, args), delay);
        };
    }

    function formatPhone(phone) {
        return phone.replace(/(\d{3})(\d{4})(\d{4})/, '$1 $2 $3');
    }

    function formatDate(dateString) {
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
        });
    }

    // UI控制
    function showLoading(show) {
        $('#loading').css('display', show ? 'flex' : 'none');
    }

    function showToast(message) {
        $('#toast').text(message || '操作失败')
            .css('right', '20px')
            .delay(3000)
            .animate({ right: '-300px' }, 300);
    }

    function updateSortUI() {
        $('#userTable th i').removeClass(`${config.sortIcons.asc} ${config.sortIcons.desc}`);
        $(`th[data-sort="${sortState.column}"] i`)
            .addClass(sortState.order === 'asc'
                ? config.sortIcons.asc
                : config.sortIcons.desc);
    }

    // 事件处理
    function handleSearch(e) {
        const keyword = e.target.value.trim();
        loadUsers(keyword);
    }
</script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</body>

</html>